package org.linlinjava.litemall.admin.service;


import com.mzwise.tunnel.service.TunnelService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallCash;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallCashService;
import org.linlinjava.litemall.db.service.LitemallSystemConfigService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.util.CashConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.Map;

@Service
public class AdminCashService {
    private final Log logger = LogFactory.getLog(AdminCashService.class);

    private final String SUCCESS = "SUCCESS";

    @Autowired
    private LitemallUserService userService;

    @Autowired
    private LitemallCashService cashService;

    @Autowired
    private TunnelService tunnelService;

    @Autowired
    private LitemallSystemConfigService systemConfigService;

    public Object check(LitemallCash resource) {
        LitemallCash cash = cashService.findById(resource.getId());
        cash.setStatus(resource.getStatus());
        cash.setReply(resource.getReply());
        if (CashConstant.STATUS_PASS.equals(resource.getStatus())) { // 同意。我，秦始皇，打钱
            Integer userId = cash.getUserId();
            LitemallUser user = userService.findById(userId);
            if (user.getBalance().compareTo(cash.getAmount())<0) { // 余额不足
                return ResponseUtil.fail(400, "余额不足");
            }
            user.setBalance(user.getBalance().subtract(cash.getAmount()).setScale(2, BigDecimal.ROUND_HALF_UP));
            userService.updateWithOptimisticLocker(user);
            Map<String, String> rule = systemConfigService.listCash();
            if ("1".equals(rule.get("litemall_cash_auto"))) {// 微信企业付款
                try {
                    Map<String, String> transfer = tunnelService.getWxTransferService().transfer(cash.getId().toString(), user.getWeixinOpenid(), cash.getAmount(), cash.getReply());
                    if (SUCCESS.equals(transfer.get("return_code")) && SUCCESS.equals(transfer.get("result_code"))) {

                    } else {
                        return ResponseUtil.fail(400, transfer.get("err_code_des"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ResponseUtil.fail(400, "微信退款失败");
                }
            }
        }
        cashService.updateById(cash);
        return ResponseUtil.ok();
    }
}
